<template>
<div>
  <div class="role-operate">
  <!-- 角色管理内容 -->
    <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
  </div>
  <!-- 放置table组件 -->
  <el-table :data="roleList">
    <!-- 放置列 -->
    <el-table-column
      prop="name"
      label="角色"
      align="center"
      width="200"
    >
      <template v-slot="{ row }">
      <!-- 条件判断 -->
        <el-input v-model="row.editRow.name" v-if="row.isEdit" size="mini"></el-input>
        <span v-else>{{ row.name }}</span>
      </template>
    </el-table-column>
    <el-table-column
      prop="state"
      label="启用"
      align="center"
      width="200"
    >
      <template v-slot="{ row }">
        <el-switch v-model="row.editRow.state" :active-value="1" :inactive-value="0" v-if="row.isEdit"></el-switch>
        <span v-else>{{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '无' }}</span>
      </template>
    </el-table-column>
    <el-table-column
      prop="description"
      label="描述"
      align="center"
    >
      <template v-slot="{ row }">
        <el-input v-model="row.editRow.description" v-if="row.isEdit" type="textarea"></el-input>
        <span v-else>{{ row.description }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="操作"
      align="center"
    >
    <template v-slot="{ row }">
      <!-- 编辑状态 -->
      <template v-if="row.isEdit">
        <el-button type="primary" size="mini" @click="btnEditOk(row)">确定</el-button>
        <el-button size="mini" @click="row.isEdit = false">取消</el-button>
      </template>
      <!-- 放置操作按钮 -->
      <!-- 非编辑状态 -->
      <template v-else>
        <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
        <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
        <el-button size="mini" type="text">删除</el-button>
        <el-popconfirm title="该角色确定删除吗？" @onConfirm="confirmDel(row.id)">
          <el-button slot="reference" style="margin-left: 10px" size="mini" type="text">删除</el-button>
        </el-popconfirm>
      </template>
    </template>
    </el-table-column>
  </el-table>
  <!-- 放置分页组件 -->
  <el-row type="flex" style="height: 60px" align="middle" justify="end">
    <el-pagination
      :page-size="pageParams.pagesize"
      :current-page="pageParams.page"
      :total="pageParams.total"
      layout="prev, pager, next"
      @current-change="changePage"
    ></el-pagination>
  </el-row>
  <!-- 放置弹层组件 -->
  <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
    <!-- 放置表单 -->
    <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleForm.name" style="width: 300px" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="启用" prop="state">
        <!-- 如果不需求校验就 不需要写prop属性 如果需要重置表单数据的话就要prop属性 -->
        <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini"></el-switch>
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width: 300px;" size="mini"></el-input>
      </el-form-item>
      <el-form-item>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button type="primary" size="mini" @click="btnOk">确定</el-button>
            <el-button size="mini" @click="btnCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!-- 放置权限弹层组件 -->
  <el-dialog title="分配权限" :visible.sync="showPermissionDialog">
    <!-- 放置权限数据 -->
    <el-tree
      ref="permTree"
      node-key="id"
      :data="permissionData"
      :props="{ label: 'name' }"
      show-checkbox
      default-expand-all
      :default-checked-keys="permIds"
    ></el-tree>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="mini" @click="btnPermissionOk">确定</el-button>
        <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</div>
</template>

<script>
import {getRoleList, addRole, updateRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { transListToTreeData } from "@/utils";
import { getPermissionList } from "@/api/permission";
export default {
  name: "Role",
  data() {
    return {
      // 角色列表
      roleList: [],
      // 分页参数
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页显示多少条,
        total: 0 // 总页数
      },
      // 控制弹层显示
      showDialog: false,
      // 角色表单
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认为 1启用 0关闭
      },
      rules: {
        name: [{
          required: true,
          message: '角色名称不能为空',
          trigger: 'blur'
        }],
        description: [{
          required: true,
          message: '角色描述不能为空',
          trigger: 'blur'
        }]
      },
      showPermissionDialog: false, // 控制权限弹层
      permissionData: [], // 权限数据
      currentRoleId: null, // 记录当前点击角色id
      permIds: [], // 用来双向绑定
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.roleList = rows
      this.pageParams.total = total
      this.roleList.forEach(item => {
        // item.isEdit = false // 添加一个属性 初始值为false
        // 数据响应式的问题 数据变化 视图更新
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象,属性名称,初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      console.log(rows)
    },
    // 点击切换页数
    changePage(newPage) {
      console.log(newPage)
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList()
    },
    // 弹层确认操作
    btnOk() {
      this.$refs.roleForm.validate(async isOk => {
        if (isOk) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          await this.getRoleList()
          this.btnCancel()
        }
      })
    },
    // 弹层取消操作
    btnCancel () {
      this.$refs.roleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    // 点击编辑行
    btnEditRow(row) {
      row.isEdit = true // 改变编辑行的状态
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 点击确定时触发
    async btnEditOk(row) {
      if (row.editRow.name && row.editRow.description) {
        // 下一步操作
        await updateRole({ ...row.editRow,id: row.id})
        // 更新成功
        this.$message.success('更新角色成功')
        // 更新显示数据 退出编辑状态
        Object.assign(row, {
          ...row.editRow,
          isEdit: false // 退出编辑模式
        })
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    // 删除角色
    async confirmDel (id) {
      // 调用删除接口
      await delRole(id)
      // 提示删除成功
      this.$message.success('删除角色成功')
      // 如果删除的是最后一个
      if (this.roleList.length === 1) this.pageParams.page--
      // 重新渲染数据
      await this.getRoleList()
    },
    // 分配权限
    async btnPermission (id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      console.log(await getRoleDetail(id))
      this.permIds = permIds
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      this.showPermissionDialog = true
    },
    // 更改权限
    async btnPermissionOk () {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      // 提示消息
      this.$message.success('角色权限分配成功')
      // 关闭弹层
      this.showPermissionDialog = false
    }
  }
}
</script>

<style scoped>
  .role-operate {
    padding: 10px;
  }
</style>
